import {
  addTask,
  deleteConvertcolumn,
  deleteTask,
  dropUserCourse,
  editConvertcolumn,
  editTask,
  getCertificateInfo,
  getConvertDetail,
  getCoursewareList,
  getExam,
  getMaterial,
  getPractice,
  getQuestionnaire,
  getTaskNotice,
  getTrainingDetail,
  getTrainingSchedule,
  getTrainingUserCourseList,
  queryConvertcolumn,
  queryConvertList,
  queryCoursewareLearn,
  queryTask,
  queryTaskDetail,
  saveConvertcolumn,
  saveMaterial,
  uploadConvertcolumn,
  queryCourseExam,
  addConvertRecord,
  updateConvertRecord,
  applyUserCert,
  applyCertRecord,
} from "@/api/training-detail"
import {saveAs} from "file-saver";
import {getUuid,setLoginInfo,getLoginInfo,removeLoginInfo} from "@/utils/auth";
import {encryptByDESModeCBCUtf8to64} from "@/utils";
import {checkUser} from "@/api/resetPwd";
import {getCoursewareInfo,playCourseware} from "@/api/courseware-study";
export default {
  handleClick(tab, event) {
    this.changeList()
  },
  changeList() {
    switch (this.activeName) {
      case 'required':
        this.getRequiredList();
        break;
      case "elective":
        this.getElectiveList();
        break;
      case "exam":
        this.getExamList();
        break;
      case "practice":
        this.getPracticeList();
        break;
      case "task":
        this.getTaskList();
        break;
      case "material":
        this.getMaterialList();
        break;
      case "convert":
        this.getConvertList();
        break;
      default:
        this.getQuestionnaireList();
    }
  },
  changeRequiredStatus(navStatus) {
    this.requiredListQuery.navStatus = navStatus;
    this.getRequiredList()
  },
  getRequiredList() {
    var data = {
      attribute: '0',
      orderName: "",
      orderSort: "",
      pageNum: this.requiredListQuery.pageNum,
      pageSize: this.requiredListQuery.pageSize,
      queryType: this.requiredListQuery.navStatus,
      tcId: this.trainingId
    }
    getTrainingUserCourseList(data).then((response) => {
      this.requiredList = response.data.list;
      this.requiredList.forEach((item, index) => {
        this.$set(this.requiredList[index], 'showCourseWare', false);
        this.$set(this.requiredList[index], 'activeName', 'course');
        this.$set(this.requiredList[index], 'courseWareList', []);
        this.$set(this.requiredList[index], 'courseExamList', []);
      })
      this.requiredTotal = Number(response.data.total)
    }).catch((err) => {
      this.$message.error(err.message || 'error')
    });
  },
  changeElectiveStatus(navStatus) {
    this.electiveListQuery.navStatus = navStatus;
    this.getElectiveList()
  },
  getElectiveList() {
    var data = {
      attribute: '1',
      orderName: "",
      orderSort: "",
      pageNum: this.electiveListQuery.pageNum,
      pageSize: this.electiveListQuery.pageSize,
      queryType: this.electiveListQuery.navStatus,
      tcId: this.trainingId
    }
    getTrainingUserCourseList(data).then((response) => {
      this.electiveList = response.data.list;
      this.electiveList.forEach((item, index) => {
        this.$set(this.electiveList[index], 'showCourseWare', false)
        this.$set(this.electiveList[index], 'activeName', 'course');
        this.$set(this.electiveList[index], 'courseWareList', []);
        this.$set(this.electiveList[index], 'courseExamList', []);
      });
      this.electiveTotal = Number(response.data.total)
    }).catch((err) => {
      this.$message.error(err.message || 'error')
    });
  },
  findECourseWare(index, courseObj) {
    courseObj.showCourseWare = true;
    var data = {
      bindYear: "",
      courseId: courseObj.courseId,
      tcId: this.trainingId
    }
    getCoursewareList(data).then((response) => {
      courseObj.courseWareList = response.data;
    }).catch((err) => {
      this.$message.error(err.message || 'error')
    });
  },
  hideECourseWare(index, courseObj) {
    courseObj.showCourseWare = false;
  },
  handleChangeTab(courseObj){
    if (courseObj.activeName == 'exam'){
      this.getCourseExam(courseObj);
    }
  },
  getCourseExam(courseObj){
    var data = {
      courseId: courseObj.courseId,
      orderNam: "",
      orderSort: "",
      pageNum: 1,
      pageSize: 10,
      tcId: this.trainingId,
    }
    queryCourseExam(data).then((response) =>{
      courseObj.courseExamList = response.data.list;
    }).catch((err) =>{
      this.$message.error(err.message)
    });
  },
  // https://yczj.ctonline.org.cn/studycourseware?trainingId=1404771076487942144&courseId=1289255947042131968&coursewareId=1289255947058909184&courseWareIndex=1
  studyCourseware(courseWareIndex, courseObj, courseWareObj) {
    if (this.endTime >= 0) {
      if (this.studyWindow && !this.studyWindow.closed) {
        const routerJump = this.$router.resolve({
          path: '/studycourseware',
          query: {
            trainingId: this.trainingId,
            courseId: courseObj.courseId,
            coursewareId: courseWareObj.id,
            courseWareIndex,
          }
        });
        this.studyWindow.location.href = routerJump.href;
        this.studyWindow.focus();
      }else {
        let routerJump = this.$router.resolve({
          path: "/studycourseware",
          query: {
            trainingId: this.trainingId,
            courseId: courseObj.courseId,
            coursewareId: courseWareObj.id,
            courseWareIndex,
          }
        });
        this.studyWindow =   window.open(routerJump.href, '_blank');
      }
    } else {
      this.$confirm('请在有效时间学习', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      })
    }
  },
  openCourseware(courseWareIndex, courseObj, courseWareObj){
    var data = {
      tcId: this.trainingId,
      tcid: this.trainingId,
      courseId: courseObj.courseId,
      coursewareId: courseWareObj.id,
    }
    getCoursewareInfo(data).then((response) =>{
      playCourseware(data).then((response) =>{
      }).catch((err) =>{});
      window.open(response.data.videoUrl)
    }).catch((err) =>{
      this.$message.error(err.message || 'error')
    });
  },
  updateProgress(courseObj, courseWareObj,courseWareList,courseWareIndex){
    var data = {
      tcId: this.trainingId,
      courseId: courseObj.courseId,
      coursewareId: courseWareObj.id,
    }
    queryCoursewareLearn(data).then((response) =>{
      if (response.data) {
        courseWareList[courseWareIndex].schedule = response.data.schedule;
        courseWareList[courseWareIndex].learnCount = response.data.learnCount;
        courseWareList[courseWareIndex].learnTime = response.data.lastStudyTime;
      }
    }).catch((err) =>{
      this.$message.error(err.message || 'error')
    });
  },
  getExamList() {
    var data = {
      orderName: "",
      orderSort: "",
      pageNum: this.examListQuery.pageNum,
      pageSize: this.examListQuery.pageSize,
      tcId: this.trainingId
    }
    getExam(data).then((response) => {
      this.examList = response.data.list;
      this.examTotal = Number(response.data.total)
    }).catch((err) => {
      this.$message.error(err.message || 'error')
    });
  },
  getPracticeList() {
    var data = {
      orderName: "",
      orderSort: "",
      pageNum: this.practiceListQuery.pageNum,
      pageSize: this.practiceListQuery.pageSize,
      tcId: this.trainingId
    }
    getPractice(data).then((response) => {
      this.practiceList = response.data.list;
      this.practiceTotal = Number(response.data.total)
    }).catch((err) => {
      this.$message.error(err.message || 'error')
    });
  },
  getMaterialList() {
    var data = {
      orderName: "",
      orderSort: "",
      pageNum: this.materialListQuery.pageNum,
      pageSize: this.materialListQuery.pageSize,
      entityId: this.trainingId
    }
    getMaterial(data).then((response) => {
      this.materialList = response.data.list;
      this.materialTotal = Number(response.data.total)
    }).catch((err) => {
      this.$message.error(err.message || 'error')
    });
  },
  //调查问卷
  getQuestionnaireList() {
    var data = {
      orderName: "",
      orderSort: "",
      pageNum: this.questionnaireListQuery.pageNum,
      pageSize: this.questionnaireListQuery.pageSize,
      tcId: this.trainingId
    }
    getQuestionnaire(data).then((response) => {
      this.questionnaireList = response.data.list;
      this.questionnaireTotal = Number(response.data.total)
    }).catch((err) => {
      this.$message.error(err.message || 'error')
    });
  },
  getTaskList(){
    getTaskNotice(this.trainingId).then((response) =>{
      this.taskNotice = response.data;
    }).catch((err) =>{
      this.$message.error(err.message || 'error')
    });
    var data = {
      tcId:this.trainingId
    }
    queryTask(data).then((response) =>{
      this.taskList = response.data.list;
      this.taskTotal = Number(this.taskNotice.taskNum) - Number(response.data.submitTotal);
    }).catch((err) =>{
      this.$message.error(err.message || 'error')
    });

  },
  getDetail() {
    getTrainingDetail(this.trainingId).then((response) => {
      this.detail = response.data;
      this.endTime = this.$utils.daysBetween(this.detail.endTime, this.$utils.getDate());
      if (this.endTime > 0) {
        this.endTimeArr = this.endTime.toString().split('')
      } else if (this.endTime == 0) {
        this.mintime()
      }
    }).catch((err) => {
      this.$message.error(err.message || 'error')
    });
  },
  mintime() {
    var time = this.detail.endTime + ' 23:59:59';
    // var time = this.detail.endTime + ' 09:32:59';
    var timer = setInterval(() => {
      this.endTimeCount = this.$utils.getTimeLeft(time);
      if (this.endTimeCount == '00:00:00') {
        this.endTime = -1;
        clearInterval(timer);
      }
    }, 1000);
  },
  getSchedule() {
    getTrainingSchedule(this.trainingId).then((response) => {
      this.tcDetail = response.data;
      this.convertFrom.convertType = response.data && response.data.configConvertType && response.data.configConvertType;
      if (this.tcDetail.isContainsCommon == '0') {
        this.activeName = "required";
        this.getRequiredList();
      }else if (this.tcDetail.isConfigConvert == '0') {
        this.activeName = "convert";
        this.getConvertList();
      } else if (this.tcDetail.isContainsElective == '0') {
        this.activeName = "elective";
        this.getElectiveList();
      } else if (this.tcDetail.isContainsExam == '0') {
        this.activeName = "exam";
        this.getExamList();
      } else if (this.tcDetail.isContainsPractice == '0') {
        this.activeName = "practice";
        this.getPracticeList()
      }else if (this.tcDetail.isContainsTask == '0') {
        this.activeName = "task";
        this.getTaskList();
      }else if (this.tcDetail.isContainsMaterial == '0') {
        this.activeName = "material";
        this.getMaterialList()
      }else if (this.tcDetail.isContainsDiscuss == '0') {
        this.activeName = "discussion";
      } else if (this.tcDetail.isContainsNaire == '0') {
        this.activeName = "questionnaire";
        this.getQuestionnaireList();
      }else {
        this.activeName = "";
      }
    }).catch((err) => {
      this.$message.error(err.message || 'error')
    });
  },
  chooseCourse(buyType) {
    this.$router.push({
      path: "/choose-course",
      query: {
        trainingId: this.trainingId,
        type: this.activeName,
        buyType,
      }
    })

  },

  toQuestionnaire(id) {
    let routerJump = this.$router.resolve({
      path: "/questionnaire",
      query: {
        id,
        trainingId: this.trainingId,
      }
    });
    window.open(routerJump.href, '_blank');
  },
  toQuestionnaireAnalysis(id) {
    let routerJump = this.$router.resolve({
      path: "/questionnaireAnalysis",
      query: {
        id,
        trainingId: this.trainingId,
      }
    });
    window.open(routerJump.href, '_blank');
  },
  toExam(paperId,courseId) {
    let routerJump = this.$router.resolve({
      path: '/exam',
      query: {
        trainingId: this.trainingId,
        paperId,
        courseId,
      }
    });
    window.open(routerJump.href, '_blank');
  },
  toPractice(paperId) {
    let routerJump = this.$router.resolve({
      path: '/practice',
      query: {
        trainingId: this.trainingId,
        paperId,
      }
    });
    window.open(routerJump.href, '_blank');
  },
  toExamAnalysis(paperId,courseId) {
    let routerJump = this.$router.resolve({
      path: '/examAnalysis',
      query: {
        trainingId: this.trainingId,
        paperId,
        courseId,
        type:"high"
      }
    });
    window.open(routerJump.href, '_blank');
  },
  downFile(path,name,resourceType,materialId){
    saveMaterial({materialId}).then((response) =>{
      saveAs(path,name+resourceType)
    }).catch((err) =>{
      this.$message.error(err.message || 'error')
    });
  },
  //退课
  dropCourse(courseId) {
    var data = {
      courseId,
      tcId: this.trainingId
    };
    dropUserCourse(data).then((response) => {
      this.$message.success("退课成功");
      window.location.reload();
    }).catch((err) => {
      this.$confirm(err.message, '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      });
    });
  },
  updateRefresh() {
    this.refresh = localStorage.getItem("resetTrainFn");
  },
  toDiscussion(){
    let routerJump = this.$router.resolve({
      path: '/discussion',
      query: {
        trainingId: this.trainingId,
      }
    });
    window.open(routerJump.href, '_blank');
  },


  /*编辑器*/
  onCreated(editor) {
    this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    this.editor = this.withGetHtml(this.editor);
  },
  withGetHtml(editor) {
    if (editor) {
      const { getHtml } = editor; // 获取当前 editor API
      const newEditor = editor;
      // 重写 getHtml
      newEditor.getHtml = () => {
        if (getHtml() === '<p><br></p>') return ''
        return getHtml()
      }
      // 返回 newEditor ，重要！
      return newEditor
    }
  },
  onChange(editor) {
    // 获取字数
    this.editLength = editor.getText().replace(/\n|\r/gm, '').length;
  },
  creatTask () {
    this.taskVisible = true;
    // this.onCreated()
  },
  submitTask (status) {
    this.$refs.taskFrom.validate(valid => {
      if (valid) {
        if (this.statusText == 'update'){
          var data = {
            conetntType: "0",
            path: this.taskFrom.filePath,
            entityid: this.trainingId,
            filename: this.taskFrom.name,
            id:this.taskFrom.id,
            status,
            type: "1"
          }
          editTask(data).then((response) =>{
            this.$message.success("提交成功")
            this.handleClose();
            this.getTaskList();
          }).catch((err) =>{
            this.$message.error(err.message || 'error')
          });
        } else {
          var data = {
            conetntType: "0",
            path: this.taskFrom.filePath,
            entityid: this.trainingId,
            filename: this.taskFrom.name,
            status,
            type: "1"
          }
          addTask(data).then((response) =>{
            this.$message.success("提交成功")
            this.handleClose();
            this.getTaskList();
          }).catch((err) =>{
            this.$message.error(err.message || 'error')
          });
        }

      } else {
        console.log('提交失败!!');
        return false
      }
    })
  },

  delTask(id){
    deleteTask(id).then((response) =>{
      this.$message.success('删除成功')
      this.getTaskList();
    }).catch((err) =>{
      this.$message.error(err.message)
    });
  },
  previewTaskContent(item){
    this.statusText = 'preview';
    this.taskFrom = {
      name: item.filename,
      content: item.content,
      fileUrl:item.fileUrl,
      filePath:item.filePath,
    }
    this.creatTask();
  },
  editTaskContent(item){
    this.statusText = 'update';
    this.taskFrom = {
      name: item.filename,
      content: item.content,
      fileUrl:item.fileUrl,
      filePath:item.filePath,
      id:item.id,
    }
    this.creatTask();
  },
  handleClose(){
    this.taskVisible = false;
    this.statusText = 'create';
    this.taskFrom = {
      name: "",
      content: "",
      id:"",
    }
  },
  taskstatusFilter(status){
    const statusMap = {
      '0': 'status-audit',
      '1': 'status-success',
      '2': 'status-error',
      '4': ''
    }
    return statusMap[status]
  },
  taskStatusNameFilter(status) {
    const statusMap = {
      '0': '已提交待审核',
      '1': '合格',
      '2': '不合格',
      '4': '待提交',
    };
    return statusMap[status]
  },

  hanldUploadSuccess(val){
    console.log(val)
  },

  hanldUpdate({fileUrl,filePath}){
    this.taskFrom.fileUrl  = fileUrl;
    this.taskFrom.filePath  = filePath;
  },
  /*折算学时*/
  openConvert(){
    this.convertVisible  =true;
    this.formReadonly  = false;
    // this.getAreaList();
  },
  closeConvert(){
    this.convertVisible  = false;
    this.convertEdit  = false;
    this.convertFrom =  {
      id:"",
      recordId:"",
      convertCredit: "",
      entityId: this.trainingId,
      convertType:  this.tcDetail.configConvertType,
      trainingTime: "",
      remark: "",
      title: "",
      trainingOrg: "",
      trainingYear: "",
      trainingContent: "",
      auditReason: "",
      resourceList: [],
    };
  },

  formatInput(value) {
    // 只允许数字和一个小数点
    const regex = /^[0-9]*\.?[0-9]*$/;
    if (!regex.test(value)) {
      this.convertFrom.convertCredit = value.replace(/[^0-9.]/g, ''); // 移除非法字符
    } else {
      this.convertFrom.convertCredit = value;
    }

    // 如果出现多个小数点，保留第一个
    const dotIndex = this.convertFrom.convertCredit.indexOf('.');
    if (dotIndex !== -1) {
      this.convertFrom.convertCredit =
        this.convertFrom.convertCredit.slice(0, dotIndex + 1) +
        this.convertFrom.convertCredit.slice(dotIndex + 1).replace(/\./g, '');
    }
  },
  handleRemove(file, fileList) {
    this.convertFrom.resourceList = this.convertFrom.resourceList.filter(item => {
      return item.filePath !== file.filePath
    })
  },
  getConvertList(){
    queryConvertList(this.trainingId).then((response) =>{
      this.convertList = response.data;
    }).catch((err) =>{
      this.$message.error(err.message)
    });
  },

  getAreaList(){
    var data = {}
    queryConvertcolumn(this.trainingId).then((response) =>{
      this.convertArea = response.data;
    }).catch((err) =>{
      this.$message.error(err.message)
    });
  },
  handleEdit(row,status){
    // this.getAreaList();
    this.convertEdit = true;
    getConvertDetail(row.id).then((response) =>{
      response.data.resourceList.forEach((item) =>{
        item.url = item.fileUrl
      })
      for (var argumentsKey in response.data) {
        this.convertFrom[argumentsKey] = response.data[argumentsKey];
      }
      var startTrainingTime = new Date(response.data.startTrainingTime);
      var endTrainingTime = new Date(response.data.endTrainingTime);
      this.convertFrom.trainingTime = [startTrainingTime,endTrainingTime];
      this.convertVisible  =true;
      if (status === '2' || status ==='3') {
        this.formReadonly = true;
      }else {
        this.formReadonly = false;
      }
    }).catch((err) =>{
      this.$message.error(err.message)
    });
  },
  handleSave(row){
    var data = {
      convertId: row.convertId,
      title: row.title,
      remark: row.remark,
      entityId: this.trainingId,
      resources: row.resourceList,
      status:"1",
      type: "0"
    }
    saveConvertcolumn(data).then((response) =>{
      this.$message.success("提交成功");
      this.getConvertList();
    }).catch((err) =>{
      this.$message.error(err.message || 'error')
    });
  },
  handleDelete(id){
    this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteConvertcolumn(id).then((response) =>{
        this.$message.success("删除成功");
        this.getConvertList();
      }).catch((err) =>{
        this.$message.error(err.message)
      })
    }).catch(() => {

    });

  },
  handleHttpUpload(options) {
    const formData = new FormData();
    formData.append('file', options.file);
    uploadConvertcolumn(formData).then((response) => {
      this.uploadSuccess(response,options.file)
    }).catch((err) => {
      this.uploadError(err,options.file)
    })
  },
  beforeUpload(rawFile) {
    const imgSize = rawFile.size / 1024 / 1024 < 1 // 小于5MB
    if (!imgSize) {
      this.$message({
        title: '温馨提示',
        message: `上传图片大小不能超过 1M！`,
        type: 'info'
      })
    }
    return  imgSize;
  },
  uploadSuccess(response, file, ) {
    this.convertFrom.resourceList.push({
      uid: file.uid, //取出组件生成的uid 解决上传闪动的问题
      filePath: response.data.filePath,
      fileUrl: response.data.fileUrl,
      url:response.data.fileUrl,
      name: file.name,
    });

    this.$message({
      title: '温馨提示',
      message: '图片上传成功！',
      type: 'success'
    })
  },
  uploadError(err, file, ) {
    console.log(err, file, )
    this.$message({
      title: '温馨提示',
      message: '图片上传失败，' + err.message,
      type: 'error'
    })
    this.convertFrom.resourceList = [];
  },
  uploadExceed(files, fileList){
    this.$message({
      title: '温馨提示',
      message: '图片最多上传8张',
      type: 'error'
    })
  },
  applyCret(){
    applyUserCert(this.trainingId).then((response) =>{
       this.$message.success(response.data);
      this.userCertRecordFlag = false;
    }).catch((err) =>{
      this.$message.error(err.message)
    });
  },

  getCertRecord(){
    applyCertRecord(this.trainingId).then((response) =>{
      this.userCertRecord = response.data;
      this.userCertRecordFlag = true;
    }).catch((err) =>{
      this.$message.error(err.message)
    });
  },
  submitConvert (status) {
    var startTrainingTime = this.$utils.parseTime2(this.convertFrom.trainingTime[0],true)
    var endTrainingTime = this.$utils.parseTime2(this.convertFrom.trainingTime[1],true)
    this.convertFrom.status = status;
    this.$refs.convertFrom.validate(valid => {
      if (valid) {
        var data = {
          startTrainingTime,
          endTrainingTime,
          status,
          type: "0",
          entityId: this.trainingId,
          resources: this.convertFrom.resourceList,
        }
        for (var validKey in this.convertFrom) {
          data[validKey] = this.convertFrom[validKey]
        }
        if (this.convertEdit) {
          updateConvertRecord(data).then((response) =>{
            this.closeConvert();
            this.getConvertList();
          }).catch((err) =>{
            this.$message.error(err.message || 'error')
          });
        }else {
          addConvertRecord(data).then((response) =>{
            this.closeConvert ();
            this.getConvertList();
          }).catch((err) =>{
            this.$message.error(err.message || 'error')
          });
        }

      } else {
        console.log('提交失败!!');
        return false
      }
    })
  },


}
